/*
 * @Description: 
 * @Autor: 商晓彬
 * @Date: 2021-06-29 16:43:44
 * @LastEditors: 商晓彬
 * @LastEditTime: 2022-02-21 10:46:00
 */
import { AfterViewChecked, Component, ElementRef, EventEmitter, Injector, Input, Output, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ModalDirective } from 'ngx-bootstrap';
import { MessageService } from '@abp/message/message.service';
import {
    BomContentServiceProxy, BomEditList, BomEditParentData, BomDesignDetailDto, CommonServiceProxy,
    MaterialsEditContentDto, MaterialsServiceProxy
} from '@shared/service-proxies/service-proxies';
import { finalize } from 'rxjs/operators';
import { MaterialCodeComponent } from './material-code/material-code.component';
import { MaterialSonComponent } from './material-son/material-son.component';
import { FileDownloadService } from '@shared/utils/file-download.service';
import { BomApprovalComponent } from '../bom-approval/bom-approval.component';
import { LazyLoadEvent, TreeNode } from 'primeng/api';

@Component({
    selector: 'addOrEditPath',
    templateUrl: './add-or-edit-path.component.html',
    styleUrls: ['./add-or-edit-path.component.less']
})
export class AddOrEditPathComponent extends AppComponentBase {
    @ViewChild('materialCode') materialCode: MaterialCodeComponent;
    @ViewChild('materialSon') materialSon: MaterialSonComponent;
    @ViewChild('bomApproval') bomApproval: BomApprovalComponent;
    //引入子组件
    @ViewChild('createOrEditModal') modal: ModalDirective;
    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();
    @Input() editData: any;  //行数据
    @Input() title: string;  //标题
    saving = false;
    active = false;
    codeFlag = false;
    form = { materialCode: '', materialname: '', model: '', sendTime: '' };
    treeData: any;
    selectedNode: any;
    parentTitle = '';
    sonTitle = '';
    rowdata = [];
    oldTree: any;
    selectRow: any = undefined;
    addFlag: boolean = false;
    display = false;
    uploadedFiles = [];
    bomUsing = false;
    sonData: any;
    secondSon: any;
    sonType = undefined;
    saveFlag = true;
    addParent = false;
    nodeLevel = undefined;
    addForm = {
        materialCode: '', materialname: '', materialProperties: 0,
        materialModel: undefined, sendTime: undefined, isUsed: true, remark: ''
    };
    modelOptions = [];
    sendTimeOptions = [];
    materialPropertiesOption = [
        {
            label: '请选择',
            value: ''
        }, {
            label: '整装',
            value: 0
        }, {
            label: '芯级',
            value: 4
        }, {
            label: '部件',
            value: 1
        }, {
            label: '组件',
            value: 2
        }, {
            label: '零件',
            value: 3
        },
    ];
    constructor(
        injector: Injector,
        private _messageService: MessageService,
        private _bomContentServiceProxy: BomContentServiceProxy,
        private _fileDownloadService: FileDownloadService,
        private _commonServiceProxy: CommonServiceProxy,
        private _materialsServiceProxy: MaterialsServiceProxy,
    ) {
        super(injector);
    }
    addSave() {
        let input = new MaterialsEditContentDto();
        input.materialNo = this.addForm.materialCode;
        input.materialName = this.addForm.materialname;
        input.materialProperty = this.addForm.materialProperties;
        input.modelId = this.addForm.materialModel;
        input.sendTimeId = this.addForm.sendTime;
        input.remark = this.addForm.remark;
        if (this.addForm.isUsed) {
            input.isUsed = 1;
        } else {
            input.isUsed = 0;
        }
        if (this.saveFlag) {
            this.saveFlag = false;
            this._materialsServiceProxy.createOrUpdateMaterialsContent(input)
                .pipe(finalize(() => { this.saving = false; }))
                .subscribe((result) => {
                    this.saveFlag = true;
                    if (result.code == 0) {
                        this._messageService.success('保存成功');
                        this.addForm.isUsed = true;
                        this.addForm.materialCode = undefined;
                        this.addForm.materialModel = undefined;
                        this.addForm.materialProperties = 0;
                        this.addForm.materialname = undefined;
                        this.addForm.remark = undefined;
                        this.addForm.sendTime = undefined;
                        this.addParent = false;
                        // this.chooseP(result.materialsContentDto);
                    } else {
                        this._messageService.error(result.message)
                    }
                });
        }
    }
    add() {
        this.addParent = true;
    }
    ngOnInit() {
        //获取型号下拉
        this.modelOptions = [
            {
                label: '请选择',
                value: undefined
            }
        ];
        this._commonServiceProxy.getModelList()
            .pipe(finalize(() => { }))
            .subscribe(result => {
                for (const item of result) {
                    let data = { label: undefined, value: undefined };
                    data.label = item.label;
                    data.value = item.value;
                    this.modelOptions.push(data);
                }
            });
    }
    onChange(event) {
        this.sendTimeOptions = [
            {
                label: '请选择',
                value: undefined
            }
        ];
        this._commonServiceProxy.getLotNoList(this.addForm.materialModel)
            .pipe(finalize(() => { }))
            .subscribe(result => {
                for (const item of result) {
                    let data = { label: undefined, value: undefined };
                    data.label = item.label;
                    data.value = item.value;
                    this.sendTimeOptions.push(data);
                }
            });
    }
    selectStatus(value) {
        switch (value) {
            case 0:
                return '编制中';
            case 1:
                return '审核中';
            case 2:
                return '被驳回';
            case 3:
                return '已发布';
            case 4:
                return '已维护';
            case 5:
                return '待维护';
            default:
                return null;
        }
    }
    submitDetail(row) {
        let input = new BomDesignDetailDto();
        input.unit1BomDosage = row.unit1BomDosage;
        input.id = row.id;
        input.remark = row.remark;
        input.materialId = row.materialId;
        input.bomDesignId = row.bomDesignId;
        input.parentId = row.parentId;
        input.btid = row.btid;
        input.yearsNo = row.yearsNo;
        this._bomContentServiceProxy.updateChildrenNode(input)
            .pipe(finalize(() => { this.saving = false; }))
            .subscribe(() => {
            });
    }
    //保存任务
    save(): void {
        //获取实体
        let input = new BomEditList();
        input.data = new BomEditParentData();
        input.children = [];
        input.data.materialsContentId = this.treeData[0].data.id;
        input.data.materialName = this.treeData[0].data.materialName;
        input.data.materialNo = this.treeData[0].data.materialNo;
        input.data.model = this.treeData[0].data.model;
        input.data.modelId = this.treeData[0].data.modelId;
        input.data.sendTime = this.treeData[0].data.sendTime;
        input.data.sendTimeId = this.treeData[0].data.sendTimeId;
        input.data.id = '00000000-0000-0000-0000-000000000000';
        input.data.bs = 0;
        input.data.insertBs = 0;
        input.children = this.treeData[0].children;
        if (this.saveFlag) {
            this.saveFlag = false;
            this._bomContentServiceProxy.addOrUpBomList(input)
                .pipe(finalize(() => { this.saving = false; }))
                .subscribe((result) => {
                    this.saveFlag = true;
                    if (result.code == 0) {
                        this._messageService.success('保存成功');
                        this.close();
                        this.modalSave.emit();
                    } else {
                        this._messageService.error(result.message)
                    }
                });
        }

    }
    //打开弹窗
    onShown(): void {
        this.form.materialCode = this.editData.materialNo;
        this.form.materialname = this.editData.materialName;
        this.form.model = this.editData.model;
        this.form.sendTime = this.editData.sendTime;
    }
    //查看新增任务
    show(): void {
        if (this.title == 'Bom维护') {
            this.initEditInfo();
        } else {
            this.addFlag = false;
        }
        this.active = true;
        this.modal.show();
    }
    //初始化修改数据
    initEditInfo() {
        this.getTreedata();
        this.addFlag = true;
    }
    getTreedata() {
        abp.ui.setBusy();
        this._bomContentServiceProxy.getBomTreeGrid(
            this.editData.id,
            undefined
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                abp.ui.clearBusy();
                this.treeData = result;
                this.treeData[0].data.levelNum = 1;
                this.expandAll();
            });
    }
    expandAll() {
        for (const node of this.treeData) {
            this.TreeExpandRecursive(node, true);
        }
    }
    private TreeExpandRecursive(node: TreeNode, isExpand: boolean) {
        if (node.data.levelNum <= 3) {
            node.expanded = isExpand;
        }
        if (node.children) {
            node.children.forEach((childNode) => {
                this.TreeExpandRecursive(childNode, isExpand);
            });
        }
    }
    //关闭事件
    close(): void {
        if (this.bomUsing) {
            this._messageService.warn("请先维护完子集用量弹窗内容！");
            return;
        }
        //清空form表单
        this.selectRow = undefined;
        this.sonType = undefined;
        this.form.model = undefined;
        this.form.materialCode = undefined;
        this.form.materialname = undefined;
        this.active = false;
        this.treeData = [];
        this.rowdata = [];
        this.oldTree = [];
        this.parentTitle = undefined;
        this.sonTitle = undefined;
        this.modal.hide();
    }
    closeParent(event) {
        this.addForm.isUsed = true;
        this.addForm.materialCode = undefined;
        this.addForm.materialModel = undefined;
        this.addForm.materialProperties = 0;
        this.addForm.materialname = undefined;
        this.addForm.remark = undefined;
        this.addForm.sendTime = undefined;
        this.addParent = false;
    }
    addSon() {
        this.nodeLevel = '芯级';
        this.sonType = 4;
        this.rowdata = [];
        this.rowdata.push(this.treeData[0].data);
        this.rowdata.push(this.treeData[0].data);
        if (this.treeData[0].children.length != 0) {
            let i = { index: this.treeData[0].children.length };
            this.rowdata.push(i);
        }
        this.secondSon = this.editData;
        this.rowdata[0].sonLevel = 1;
        this.sonTitle = "物料选择";
        this.oldTree = this.treeData;
        this.treeData = [];
        this.materialSon.show();
        this.selectRow = undefined;
    }
    showMaterCode() {
        if (!this.addFlag) {
            this.parentTitle = "父级物料选择";
            this.materialCode.show();
        }
    }
    chooseP(row) {
        this.form.materialCode = row.materialNo;
        this.form.materialname = row.materialName;
        this.form.model = row.model;
        row.sonLevel = 1;
        row.levelRelationship = 1;
        this.treeData = [{ data: row, children: [] }];
        this.expandAll();
    }
    chooseS(row) {
        if (row.length != 0) {
            if (this.addFlag) {
                setTimeout(() => {
                    if (this.selectRow == undefined) {
                        for (const item of row) {
                            let data = new BomEditList();
                            data.children = [];
                            data.data = item.data;
                            this.oldTree[0].children.push(data);
                        };
                    } else {
                        let result = this.getAddTreeChildren(this.oldTree[0].children, this.selectRow.id)
                        for (const item of row) {
                            let data = new BomEditList();
                            data.children = [];
                            data.data = item.data;
                            result.children.push(data);
                        };
                    }
                    this.treeData = this.oldTree;
                }, 10);
            } else {
                if (row[0].sonLevel == 2) {
                    for (const item of row) {
                        let data = new BomEditList();
                        data.children = [];
                        data.data = item;
                        this.treeData[0].children.push(data);
                    };
                } else if (row[0].sonLevel == 3) {
                    let result = this.getTreeRecursion(this.treeData[0].children, this.selectRow.sonId, 2);
                    for (const item of row) {
                        let data = new BomEditList();
                        data.children = [];
                        data.data = item;
                        result.children.push(data);
                    };
                } else if (row[0].sonLevel == 4) {
                    let result = this.getTreeRecursion(this.treeData[0].children, this.selectRow.sonId, 3);
                    for (const item of row) {
                        let data = new BomEditList();
                        data.children = [];
                        data.data = item;
                        result.children.push(data);
                    };
                } else if (row[0].sonLevel == 5) {
                    let result = this.getTreeRecursion(this.treeData[0].children, this.selectRow.sonId, 4);
                    for (const item of row) {
                        let data = new BomEditList();
                        data.children = [];
                        data.data = item;
                        result.children.push(data);
                    };
                }
            }
        } else {
            this.treeData = this.oldTree;
        }
    }
    getAddTreeChildren(data ,current) {
        var result = null;
        if (!data) {
            // return; 中断执行
            return;
        }
        for (var i in data) {
            if (result != null) {
                break;
            }
            var item = data[i];
            // 通过id找到树结构相应节点 找到则跳出
            if (item.data.id == current) {
                result = item;
                break;
            } else if (item.children && item.children.length > 0) {
                result = this.getAddTreeChildren(item.children, current);
            }
        }
        return result;
    }
    // 递归循环树级结构 获取对象 通过物料ID 递归
    getTreeRecursion(data, current, level) {
        var result = null;
        if (!data) {
            // return; 中断执行
            return;
        }
        for (var i in data) {
            if (result != null) {
                break;
            }
            var item = data[i];
            // 通过id找到树结构相应节点 找到则跳出
            if (item.data.sonId == current && item.data.sonLevel == level) {
                result = item;
                break;
            } else if (item.children && item.children.length > 0) {
                result = this.getTreeRecursion(item.children, current, level);
            }
        }
        return result;
    }
    addSonData(row, node) {
        this.sonType = 1;
        this.secondSon = undefined;
        this.rowdata = [];
        this.rowdata.push(this.treeData[0].data);
        this.rowdata.push(row);
        if (node.node.children.length != 0) {
            let i = { index: node.node.children.length };
            this.rowdata.push(i);
        }
        this.nodeLevel = row.materialTypeName;
        this.selectRow = row;
        this.sonTitle = "选择子集";
        this.oldTree = this.treeData;
        this.treeData = [];
        this.materialSon.show();
    }
    import(row) {
        this.rowdata = [];
        this.rowdata.push(this.treeData[0].data);
        this.rowdata.push(row);
        this.display = true;
    }
    /**
    * 下载模板
    */
    down() {
        let url = "http://localhost:4200/assets/common/excel/DesignBom.xls";
        window.open(url);
        URL.revokeObjectURL(url);
    }
    myUploader(event) {
        abp.ui.setBusy();
        let files = { data: undefined, fileName: event.files[0].name };
        files.data = event.files[0];
        this._bomContentServiceProxy.getExcelToBomDesignContent(
            files,
            this.rowdata[1].id,
        ).pipe(finalize(() => this.primengSonTableHelper.hideLoadingIndicator())).subscribe(result => {
            abp.ui.clearBusy();
            if (result.code == 0) {
                this._messageService.success("导入成功！");
                this.uploadedFiles = [];
                this.display = false;
                this.getTreedata();
            } else {
                this._messageService.error(result.message);
                this.uploadedFiles = [];
                this.display = false;
            }
        });
    }
    delete(row) {
        if (this.addFlag) {
            this.message.confirm(
                '确认删除' + row.materialNo + '吗',
                (isConfirmed) => {
                    if (isConfirmed) {
                        if (this.saveFlag) {
                            this.saveFlag = false;
                            this._bomContentServiceProxy
                                .deleBomNode(row.id)
                                .subscribe((result) => {
                                    this.saveFlag = true;
                                    if (result.code == 0) {
                                        // this.getTreedata();
                                        this.oldTree = this.treeData;
                                        this.treeData = [];
                                        this.deleteRecursion(this.oldTree, row.id, row.levelNum);
                                        setTimeout(() => {
                                            this.treeData = this.oldTree;
                                        }, 10)
                                        this._messageService.success('删除成功');
                                    } else {
                                        this._messageService.error(result.message)
                                    }
                                });
                        }

                    }
                }
            );
        } else {
            this.oldTree = this.treeData;
            this.treeData = [];
            let rs = this.deleteRecursion(this.oldTree, row.sonId, row.sonLevel);
            if (!rs) {
                this._messageService.warn("请先删除子集！");
            }
            setTimeout(() => {
                this.treeData = this.oldTree;
            }, 10)
        }

    }
    deleteRecursion(data, current, level) {
        var result = null;
        if (!data) {
            // return; 中断执行
            return;
        }
        for (var i in data) {
            if (result != null) {
                break;
            }
            var item = data[i];
            // 通过id找到树结构相应节点 找到则跳出
            if (item.data.id == current && item.data.levelNum == level) {
                if (item.children && item.children.length > 0) {
                    result = false;
                    break;
                } else {
                    data.splice(i, 1);
                    // for (let rs in data) {
                    //     let row = data[rs].data;
                    // let str = row.levelRelationship.split('.');
                    // let index = str.length;
                    // if (index == 2) {
                    //     row.levelRelationship = str[0] + '.' + (parseInt(rs) + 1);
                    // } else {
                    //     row.levelRelationship = str[0] + '.' + str[1] + '.' + (parseInt(rs) + 1);
                    // }
                    // }
                    result = true;
                    break;
                }
            } else if (item.children && item.children.length > 0) {
                result = this.deleteRecursion(item.children, current, level);
            }
        }
        return result;
    }
    getSonTreedata(row?: any) {
        this.saveFlag = false;
        this._bomContentServiceProxy.getBomChildTreeGrid(
            row.id,
            undefined
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.saveFlag = true;
                this.sonData = [];
                this.sonData.push(result);
                this.expandSonAll();
            });
    }
    expandSonAll() {
        this.sonData[0].expanded = true;
        for (const node of this.sonData[0].children) {
            this.TreeExpandRecursive(node, true);
        }
    }
    update(row) {
        this.getSonTreedata(row);
        this.bomUsing = true;
    }
    onHide(event) {
        this.bomUsing = false;
        this.sonData = [];
        this.getTreedata();
    }
    // export() {
    //      //导出
    //      this._bomContentServiceProxy.getBomContentToExcel(
    //         this.editData.id
    //     ).pipe(finalize(() => this.primengSonTableHelper.hideLoadingIndicator())).subscribe(result => {
    //         this._fileDownloadService.downloadTempFile(result);
    //     });
    // }
    saveToApproval() {
        if (this.findMateial(this.sonData)) {
            this._messageService.error('请先维护完标准件的年代号');
            return;
        }
        if (!this.saveFlag) {
            return;
        }
        this.bomApproval.show();
    }
    backToApproval() {
        this.onHide(1);
    }
    findMateial(data) {
        var result = null;
        if (!data) {
            // return; 中断执行
            return;
        }
        for (var i in data) {
            if (result != null) {
                break;
            }
            var item = data[i];
            // 通过id找到树结构相应节点 找到则跳出
            if (item.data.materialSegmentationName != null) {
                if (item.data.materialSegmentationName == '标准件') {
                    if (item.data.yearsNo == null || item.data.yearsNo == undefined || item.data.yearsNo == '') {
                        result = true;
                        break;
                    }
                }
            }
            if (result == null && item.children) {
                result = this.findMateial(item.children);
            } else {
                result = false;
            }
        }
        return result;
    }
}
